<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 幕小铺科技（大连）有限公司 [ http://www.XXX.com ]
// +----------------------------------------------------------------------
// | 2020/03/14 jason wang
// +----------------------------------------------------------------------
namespace app\user_center\logic\user;
use think\facade\Hook;
use think\DB;

class Userlogic{

	/**
     * 手机验证码登录	
     * @param  int $mobile  		手机号码
     * @param  int $code    		手机6位验证码
     * @param  int $f_uid    	推荐码
     * @param  int $create_time    	注册时间（预置用户生成）
     * @param  int $mobile_type     短信类型
     * @param  int $login_type     登录类型 1 手机登录(默认) 2 WEB端登录
     * @author jason wang <120907037@qq.com>
     * @return array_out
     */
    public function login_mobile($mobile, $code, $f_uid = 0, $create_time = '', $mobile_type = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'mobile' 		=> $mobile,
                'code'   		=> $code,
                'mobile_type'   => $mobile_type,
                'create_time'   => $create_time,
                'f_uid'   		=> $f_uid,
            ]; 
			/********行为参数赋值（*）********/
			
			/********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            };
            /********前置行为********/

            /********业务逻辑********/
            $result1 = model('user_center/UcMemberMobile', 'model\user') -> getDataByMobile($mobile);//获取用户信息
			if($result1['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error1');
			}
            $uid = $result1['data'] -> uid;

            $result = self::getUserinfoByUserInfo($uid);//获取用户详情
			if($result['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error2');
			}
			
            /********业务逻辑********/
                
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result['data']);
            /********逻辑返回********/
        } catch (\Exception $e) {
            // 回滚事务
			DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }
    	
    }

    /**
     * 通过token获取手机号
     * @param  string $access_code      一键登陆校验token
     * @param  string $mobile  	        手机号
     * @author shiqiang
     * @return array_out
     */
    public function login_mobile_obtain($access_code){

        DB::startTrans();//启动事务

        try{
            /********行为参数赋值（*）********/
            $params = [
                'access_code'   => $access_code,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            };
            /********前置行为********/

            /********业务逻辑********/
            //通过token换取手机号
            $result = controller('VerifyMobile', 'logic\user') -> verifyMobile($access_code);

            if($result['code'] < 0){
                DB::rollback();
                return array_out(-1005, $result['message']);
            }
            $result = self::login_mobile_oneclick($result['data']);
            if($result['code'] < 0){
                DB::rollback();
                return array_out(-1005, $result['message']);
            }
            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result['data']);
            /********逻辑返回********/
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }
    }

    /**
     * 手机一键登录
     * @param  string $access_code      code
     * @param  string $mobile  	        手机号
     * @author shiqiang
     * @return array_out
     */
    public function login_mobile_oneclick($mobile){
        DB::startTrans();//启动事务

        try{
            /********行为参数赋值（*）********/
            $params = [
                'mobile'   => $mobile,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            };
            /********前置行为********/

            /********业务逻辑********/
            $result1 = model('user_center/UcMemberMobile', 'model\user') -> getDataByMobile($mobile);//获取用户信息
            if($result1['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error1');
            }
            $uid = $result1['data'] -> uid;

            $result = self::getUserinfoByUserInfo($uid);//获取用户详情
            if($result['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error2');
            }

            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result['data']);
            /********逻辑返回********/
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }

    }
	
	/**
     * 微信登陆/注册
     * @param  string $openid  用户openid
     * @param  string $nick_name
     * @param  string $avatar_url
     * @param  string $unionid
     * @author shiqiang
     * @return array_out
     */
	public function register_wechat($openid ,$nick_name, $avatar_url, $unionid){
		DB::startTrans();//启动事务
		try{
			$params = [
                'openid'    	=> $openid,
                'nick_name' 	=> $nick_name,
                'avatar_url'    => $avatar_url,
                'unionid'   	=> $unionid,
            ];
			/********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/
            $result = model('UcMemberWechat', 'model\user') -> getDataByUnionid($unionid);//获取用户信息
			if($result['code'] < 0){
			    //未登陆过添加条数据
                $result1 = model('UcMemberWechat', 'model\user') -> addData(0, $openid, $unionid, $nick_name, $avatar_url);
                if(!$result1){
                    DB::rollback();
                    return array_out(-1005, 'error1');
                }
                $result = model('UcMemberWechat', 'model\user') -> getDataByUnionid($unionid);//获取用户信息
			}
			$uid = $result['data'] -> uid;
			if($uid < 1){ //未绑定用户 绑定手机号!
                $result2['data']['mobile'] 	= 0;
            }else{
                $result2 = self::getUserinfoByUserInfo($uid);//获取用户详情
                if($result2['code'] < 0){
                    DB::rollback();
                    return array_out(-1005, 'error2');
                }
            }
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			DB::commit();
            return array_out(200, 'success', $result2['data']);
        } catch (\Exception $e) {
            // 回滚事务
           DB::rollback();
           return array_out(-9999, $e -> getMessage());
        }
	}
	
	/**
     * 苹果用户登陆/注册
     * @param  string $apple_id  苹果用户id
     * @param  string $nick_name
     * @param  string $avatar_url
     * @author shiqiang
     * @return array_out
     */
	public function register_apple($apple_id ,$nick_name, $avatar_url = ''){
		DB::startTrans();//启动事务
		try{
			$params = [
                'apple_id'   => $apple_id,
                'nick_name' => $nick_name,
                'avatar_url'=> $avatar_url,
            ];
			/********前置行为********/
			/*
			 * 1.验证是否注册过
			 * 2.没注册过 - 注册账号 / 否则略
			 */
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

            $result = model('UcMemberApple', 'model\user') -> getDataByAppleid($apple_id);//获取用户信息
            if($result['code'] < 0){
                if($nick_name == ''){
                    $nick_name='ele_'.mt_rand(100000,999999);
                }
                //未登陆过添加条数据
                $result1 = model('UcMemberApple', 'model\user') -> addData(0, $apple_id, $nick_name, $avatar_url);
                if(!$result1){
                    DB::rollback();
                    return array_out(-1005, 'error1');
                }
                $result = model('UcMemberApple', 'model\user') -> getDataByAppleid($apple_id);//获取用户信息
            }
			$uid = $result['data'] -> uid;

            if($uid < 1){ //未绑定用户 绑定手机号!
                $result2['data']['mobile'] 	= 0;
            }else{
                $result2 = self::getUserinfoByUserInfo($uid);//获取用户详情
                if($result2['code'] < 0){
                    DB::rollback();
                    return array_out(-1005, 'error2');
                }
            }
            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			DB::commit();
            return array_out(200, 'success', $result2['data']);
        } catch (\Exception $e) {
            // 回滚事务
           DB::rollback();
           return array_out(-9999, $e -> getMessage());
        }
	}

	/**
     * 发送短信
     * @param  int $uid  	用户ID(非必传)
     * @param  int $mobile  手机号码
     * @param  int $type    验证码发送类型 0注册/登录 1找回密码 2更换手机（旧） 3绑定手机 4更换手机（新）	
     * @author shiqiang
     * @return array_out
     */
    public function sms_sending($uid, $mobile, $mobile_type){
		DB::startTrans();//启动事务
        try{
			$params = [
                'uid' 			=> $uid,
                'mobile' 		=> $mobile,
                'mobile_type'   => $mobile_type,
            ];
           /********前置行为********/
			// 1. 发送短信校验
			// 2. 更换新手机号 校验
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/
			
			switch ($mobile_type) {
				case 0://
					$template_code = 'SMS_193795800';
					break;
				case 1:
					$template_code = 'sms_1';
					break;
				case 2://更换手机旧
					//验证旧手机号码是否存在
					$result = model('UcMemberMobile', 'model\user') -> getDataByCheck($uid, $mobile);
					if(empty($result['data'])) return array_out(-1002,'请输入正确的原手机号');
					
					$template_code = 'SMS_199798688';
					break;
				case 3://绑定手机
					$template_code = 'SMS_199808753';
					break;
				case 4://更换新的手机
					$template_code = 'SMS_199808756';
                    break;
                case 5://企业认证
					$template_code = 'SMS_199773834';
                    break;    
			}
            //判断144 直接发送成功
            if($mobile > 14400000000 && $mobile <= 14499999999){
                return array_out(200, 'success');
            }

			$code = rand(1111,9999);
			//发送短信
			$smsSend = controller('SmsSendlogic', 'logic\user') -> sendSms($mobile, $code, $template_code);
			if($smsSend['code'] > 0){
				$result = model('UcMemberMobileSendcode', 'model\user') -> addData($mobile, $code, $mobile_type);
				if($result['code'] < 0){
					DB::rollback();
					return array_out(-1005, 'error');
				}
			}else{
				DB::rollback();
				return array_out(-1005, $smsSend['message']);
			}
			
		    /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			
			DB::commit();
			return array_out(200, 'success');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }
    	
    }
	
	
	/**
     * 用户详情
     * @param  int $user_id   用户id
     * @param  int $user_uid  被查询用户id
     * @param  string $refresh_token
     * @author shiqiang <120907037@qq.com>
     * @return array_out
     */
    public function get_user_info($user_id, $user_uid){
        try{
			$params = [
                'user_id' 	=> $user_id,
                'user_uid'   => $user_uid,
            ];
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/

			$result = model('user_center/Member', 'model\user') -> getUserinfoByUseruid($user_uid);
			if($result['code'] < 0){
				return array_out(-1005, 'error');
            }
            $result = $result['data'];

            //是否关注
            $follow = model('user_center/UcMemberFollow', 'model\user') -> getDataByFollow($user_id, $result->uid);
            $isFollow = $follow['code'] == 200 ? 1 : 0;
			
            $age = getAge(strtotime($result -> birthday));
            
			$res = [];
			$res['userId'] 			= (int)$result -> uid;
			$res['nickName'] 		= (string)$result -> nick_name;
			$res['avatorUrl'] 		= (string)get_avatar_user($result -> uid);
            $res['autograph'] 		= (string)$result -> autograph;
            $res['title'] 		    = (string)$result -> title;
			$res['sex'] 			= (int)$result -> sex;
			$res['birthday'] 		= (string) date('Y-m-d', strtotime($result -> birthday));
            $res['age'] 			= $age;
            //$res['mobile'] 			= (int)$result -> get_uc_member_mobile -> mobile;
			$res['bePraisedTimes'] 	= (int)$result -> get_uc_member_count -> be_praised_times;
			$res['followTimes'] 	= (int)$result -> get_uc_member_count -> follow_times;
			$res['fansTimes'] 		= (int)$result -> get_uc_member_count -> fans_times;
			$res['worksTimes'] 		= (int)$result -> get_uc_member_count -> works_times;
            $res['praisedTimes'] 	= (int)$result -> get_uc_member_count -> praised_times;
            $res['hotNum'] 		    = (int)$result -> get_uc_member_count -> hot_num;
            $res['isFollow'] 	    = (int)$isFollow;//是否关注
            $res['balance'] 	    = (string)$result -> balance;
            //隐私设置
            $res['privacyFansFollow'] 	= (int) ($result -> get_uc_member_privacy ? $result -> get_uc_member_privacy-> fans_follow_auth : 0);//
			
			/********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/
			
			return array_out(200, 'success', $res);
        } catch (\Exception $e) {
            return array_out(-9999, $e -> getMessage());
        }
    }
	
    /**
     * 刷新accesstoken
     * @param  int $uid  用户id
     * @param  string $refresh_token
     * @author jason wang <120907037@qq.com>
     * @return array_out
     */
    public function refresh_token($uid, $refresh_token){
		DB::startTrans();//启动事务
        try{
			$params = [
                'uid' => $uid,
                'refresh_token'   => $refresh_token,
            ];
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/
			
            //生成新的access_token 和 refresh_token
			$result = model('UcMemberAuthtoken', 'model\user') -> updateDataByUid($uid);
			if($result['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error');
			}
			
			$result = self::getUserinfoByUserInfo($uid,1);//获取token信息
			if($result['code'] < 0){
				DB::rollback();
				return array_out(-1005, 'error');
			}
			
			/********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			DB::commit();
			return array_out(200, 'success', $result['data']);
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }
    }
	
	/**
     * 获取行业
     * @author shiqiang
     * @return array_out
     */
    public function get_base_industry_classification(){
		DB::startTrans();//启动事务
        try{
			$params = [
            ];
            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            }
            /********前置行为********/
			
			$result = model('BaseIndustryClassification', 'model\user') -> field('id,title') -> order('sort asc,create_time desc') -> select();
			if(!empty($result)){
				$result = $result -> toArray();
			}
			/********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

			DB::commit();
			return array_out(200, 'success', $result);
        } catch (\Exception $e) {
			DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }
    }
	
	//重组用户数据
	public function getUserinfoByUserInfo($uid, $type = 0){
        $up_token = model('user_center/UcMemberAuthtoken', 'model\user') ->  updateDataByUid($uid);//更新用户权限token
        if($up_token['code'] < 0){
            DB::rollback();
            return array_out(-1005, 'error_access_token');
        }

		$result = model('user_center/Member', 'model\user') -> getUserinfoByUid($uid);//dump(model('Member', 'model\user') -> getLastSql());
		if($result['code'] < 0){
			return array_out(-1005, 'error');
		}
		
		$result = $result['data'];
		$data = [];
		$authToken = [];
		//token数据
		$authToken['accessToken'] 			 = (string)$result->get_uc_member_authtoken->access_token;
		$authToken['accessTokenExpireIn']	 = (string)$result->get_uc_member_authtoken->access_token_expire_in;
		$authToken['accessTokenExpireTime']  = (string)$result->get_uc_member_authtoken->access_token_expire_time;
		$authToken['refreshToken'] 			 = (string)$result->get_uc_member_authtoken->refresh_token;
		$authToken['refreshTokenExpireIn'] 	 = (string)$result->get_uc_member_authtoken->refresh_token_expire_in;+
		$authToken['refreshTokenExpireTime'] = (string)$result->get_uc_member_authtoken->refresh_token_expire_time;
		//dump($result);
		if($type == 1){
			return array_out(200, 'success', $authToken);
		}
        //权限组
        $roles = [];//dump($result);
        $roles_info = [];//权限组对应的id
        if(isset($result->get_uc_member_mobile -> mobile) && $result->get_uc_member_mobile -> mobile > 14400000000 && $result->get_uc_member_mobile -> mobile<14500000000){
            $roles[] = 'artist';
        }
        //$roles[] = 'artist';//默认全部是 艺人状态
        $artist_status = isset($result -> get_uc_attestation_artist) ? $result -> get_uc_attestation_artist -> artist_status : 0;
        if($artist_status == 1) $roles[] = 'artist';

        $attestation_status = isset($result -> get_uc_attestation) ? $result -> get_uc_attestation -> attestation_status : 0;//dump($result);
        if($attestation_status == 1) $roles[] = 'attestation';
		
		$erp_admin_user = $result -> get_erp_admin_user;
		if(!empty($erp_admin_user)){
			foreach($erp_admin_user as $key => $value){
				switch($value['user_type']){
					case 1;
						$roles[] = 'erp_admin';
						break;
					case 2;
						$roles[] 	= 'erp_store';
						
						$warehouse = model('erp/ErpStoreWarehouse') -> where('store_id', $value['store_id']) -> find();
						$warehouse_id = 0;
						if(!empty($warehouse)){
							$warehouse_id = $warehouse['warehouse_id'];
						}
						
						$roles_info[] = ['store_id' => $value['store_id'], 'warehouse_id' => $warehouse_id];
						break;
					case 3;
						$roles[] = 'admin_video_audit';
						break;
					case 4;
						$roles[] = 'user_video_audit';
						break;
				}
			}
		}
		
        
		$data['userId'] 	= (int)$result->uid;
		$data['nickName'] 	= (string)$result->nick_name;
		$data['avatorUrl']	= (string)get_avatar_user($result->uid);
		$data['mobile'] 	= 0;
        $data['openid'] 	= '';
        $data['unionid'] 	= '';
        $data['appleId'] 	= '';
        $data['authToken'] 	= $authToken;
        $data['roles'] 	    = $roles;
        $data['rolesInfo'] 	= $roles_info;
		
		if(!empty($result->get_uc_member_mobile)){
			$data['mobile'] = (int)$result->get_uc_member_mobile->mobile;
		}
		if(!empty($result->get_uc_member_wechat)){
			$data['openid']  = (string)$result->get_uc_member_wechat->open_id;
			$data['unionid'] = (string)$result->get_uc_member_wechat->unionid;
		}
		if(!empty($result->get_uc_member_apple)){
			$data['appleId']  = (string)$result->get_uc_member_apple->apple_id;
		}
		return array_out(200, 'success', $data);
	}




    /**
     * 手机验证码登录 张萌用的
     * @param  int $mobile  		手机号码
     * @param  int $code    		手机6位验证码
     * @param  int $balance    	    余额
     * @author shiqiang
     * @return array_out
     */
    public function login_mobile_balance($mobile, $code, $f_uid, $balance = 0){
        DB::startTrans();//启动事务
        try{
            /********行为参数赋值（*）********/
            $params = [
                'mobile' 		=> $mobile,
                'code'   		=> $code,
                'f_uid'   		=> $f_uid,
                'balance'   	=> $balance,
            ];
            /********行为参数赋值（*）********/

            /********前置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'before');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1002, $hook_rel['message']);//前置错误 -1002
            };
            /********前置行为********/

            /********业务逻辑********/
            $result1 = model('user_center/UcMemberMobile', 'model\user') -> getDataByMobile($mobile);//获取用户信息
            if($result1['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error1');
            }
            $uid = $result1['data'] -> uid;

            $result = self::getUserinfoByUserInfo($uid);//获取用户详情
            if($result['code'] < 0){
                DB::rollback();
                return array_out(-1005, 'error2');
            }

            /********业务逻辑********/

            /********后置行为********/
            $hook_rel = logic_hook($action = __FUNCTION__, $params, 'after');
            if($hook_rel['code'] < 0){
                DB::rollback();
                return array_out(-1003, $hook_rel['message']);//后置错误 -1003
            }
            /********后置行为********/

            /********逻辑返回********/
            DB::commit();
            return array_out(200, 'success', $result['data']);
            /********逻辑返回********/
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return array_out(-9999, $e -> getMessage());
        }

    }
}